package token

import (
	"errors"
	"github.com/golang-jwt/jwt/v5"
	"math/rand"
	"time"
)

type MyCustomClaims struct {
	UserID int
	//Username   string
	//GrantScope string
	jwt.RegisteredClaims
}

// 签名密钥
const sign_key = "74AE4F44911304C9E9EE6248C4657CB4"

// 随机字符串
var letters = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

func randStr(strLen int) string {
	randBytes := make([]rune, strLen)
	for i := range randBytes {
		randBytes[i] = letters[rand.Intn(len(letters))]
	}
	return string(randBytes)
}

func GenerateToken(userId int) (string, error) {
	claim := MyCustomClaims{
		UserID: userId,
		//GrantScope: "read_user_info",
		RegisteredClaims: jwt.RegisteredClaims{
			//Issuer:    "Auth_Server",                                   // 签发者
			//Subject:   "Tom",                                           // 签发对象
			//Audience:  jwt.ClaimStrings{"Android_APP", "IOS_APP"},      //签发受众
			//ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),   //过期时间
			//NotBefore: jwt.NewNumericDate(time.Now().Add(time.Second)), //最早使用时间
			IssuedAt: jwt.NewNumericDate(time.Now()), //签发时间
			ID:       randStr(10),                    // wt ID, 类似于盐值
		},
	}
	token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claim).SignedString([]byte(sign_key))
	return token, err
}

func ParseToken(tokenString string) (*MyCustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(sign_key), nil //返回签名密钥
	})
	if err != nil {
		return nil, err
	}

	if !token.Valid {
		return nil, errors.New("claim invalid")
	}

	claims, ok := token.Claims.(*MyCustomClaims)
	if !ok {
		return nil, errors.New("invalid claim type")
	}

	return claims, nil
}
